package server;

import java.util.LinkedList;
import twitter4j.Status;
import common.Tweet;

public class TweetParser extends Thread {

	private StatusStack rawstack;
	private TagStack tags;
	private ParsedTweetStack stack;

	public TweetParser(Handler h) {
		this.rawstack = new StatusStack();
		this.stack = h.getStack();
		tags = new TagStack();
	}

	public StatusStack getStack() {
		return rawstack;
	}

	public synchronized TagStack getStags() {
		return tags;
	}

	public synchronized void modifyTags(TagStack tags) {

		this.tags = tags;
		System.out.println("Parser tags altered:");
		System.out.println(tags.getlistStack());
	}

	public void run() {

		while (true) {
			if (rawstack.isEmpty()) {
				try {
					System.out.println("Lista de Status vazia");
					//Thread.sleep(10000);
					synchronized (rawstack){
						rawstack.wait();
					}
				} catch (InterruptedException e) {
					continue;
				} catch (Exception e) {
					System.out.println("Deu bode");
					System.exit(0);
					continue;
				}
			} else {
				System.out.println("Status arrived at parser");
				if (getStags().isEmpty()) {
					rawstack.pop();
				} else {
					Status s = rawstack.pop();
					Tweet t = createTweet(s);
					LinkedList<String> ori = getStags().getlistStack();
					String msg = s.getText();
					LinkedList<String> existing = new LinkedList<String>();
					int range = ori.size();
					for (int i = 0; i < range; i++) {
						if (msg.toLowerCase()
								.contains(ori.get(i).toLowerCase())) {
							existing.add(ori.get(i));
						}

					}
					ParsedTweet p = new ParsedTweet(t, existing);
					stack.push(p);
					System.out.println("Parsed tweet " + p.getTweet().getId()
							+ " sent to handler... tags: " + p.getTags());
				}

			}
		}

	}

	private Tweet createTweet(Status s) {
		Tweet t = new Tweet();
		t.setId(s.getId());
		t.setImageURL(((s.getUser().getProfileImageURL()).toString()));
		t.setName(s.getUser().getName());
		t.setScreenname(s.getUser().getScreenName());
		t.setUserURL();
		t.setMsg(s.getText());
		return t;
	}

}
